/**
 * /framework/common/download-file
 * 下载文件

 * @param string file
 * @return mixed
 */
window.$ExportExcel = {
    _ColumnItems:[],
    _TablesData:[],
    _Options:{
        sheet:'Sheet1',
        fileName:'导出文件',
    },

    column:function (column){
        $ExportExcel._ColumnItems = column;
        return $ExportExcel;
    },

    fileName:function (file_name){
        $ExportExcel._Options.fileName = (file_name?file_name:'导出文件');
        return $ExportExcel;
    },

    sheet:function (sheet){
        $ExportExcel._Options.sheet = (sheet?sheet:'Sheet1');
        return $ExportExcel;
    },

    export:function(page) {
        page = page?parseInt(page):1;
        $App.tablesGetExportTableList(function (res, last_page){
            if(res.length > 0 ){
                $ExportExcel._TablesData = $ExportExcel._TablesData.concat(res);
            }
            if(last_page > page){
                $ExportExcel.export(page += 1 );return true;
            }else {
                $ExportExcel.ExportEventEntities();return true;
            }
        }, page);
        return false;
    },

    ExportEventEntities:function() {
        if($ExportExcel._TablesData.length < 1){
            return false;
        }
        // 用于替换数据中的换行符，是其可以在单元格内正常显示
        const wrapMark = '<br style="mso-data-placement:same-cell;"/>';
        // 设置单元格数据显示为文本格式，避免过大的数字以科学计数法的形式显示
        const tdTagHeader = `<td style="mso-number-format:'\@'">`;
        let dataStr = '<tr>'
        $ExportExcel._ColumnItems.forEach(function (column) {
            dataStr += `${tdTagHeader + column.label}</td>`;
        });
        dataStr += '</tr>';
        $ExportExcel._TablesData.forEach(function(item) {
            dataStr += '<tr>'
            $ExportExcel._ColumnItems.forEach(function (column){
                var values = $ExportExcel._ColumnFormatMap(item, column);
                // 这种方式本质是导出 html 文件，html 中连续的空格符会被合并成一个显示
                // replace(/ /g, '&nbsp;') 将空格符替换成 &nbsp; 使其可以正常显示
                dataStr += tdTagHeader + `${values}`.replace(/ /g, '&nbsp;').replace(/\n/g, wrapMark) + '</td>';
            });
            dataStr += '</tr>'
        });
        const template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
        <head><meta charset="UTF-8" />
        <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${$ExportExcel._Options.sheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/>
        </x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${dataStr}</table></body></html>`;
        const link = document.createElement("a");
        link.href = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(template))) ;
        link.download = $ExportExcel._Options.fileName + ".xls";
        link.style.display = 'none';
        link.click();
    },

    //
    // exportToExcel:function(data, fileName) {
    //     var csv = this.convertToCSV(data); // 将数据转换为CSV格式
    //     var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); // 创建Blob对象
    //     var url = URL.createObjectURL(blob); // 转换为URL
    //     var link = document.createElement('a'); // 创建<a>元素
    //     link.setAttribute('href', url);
    //     link.setAttribute('download', `${fileName}.csv`);
    //     link.style.visibility = 'hidden';
    //     document.body.appendChild(link);
    //     link.click(); // 触发下载
    //     document.body.removeChild(link); // 清理
    // },

    _ColumnFormatMap:function (item, column){
        var values = item[column.key]?item[column.key]:'';
        switch (column.key){
            case 'stated':
                return (parseInt(values) === 10)?'启用':'禁用';
                break;
            case 'updated_at':
            case 'created_at':
                return $Utils.formatDate('yyyy-MM-dd hh:mm:ss', values);
        }
        if((typeof column.format) === 'undefined'){
            return item[column.key];
        }
        switch (column.format){
            case 'datetime':
                return $Utils.formatDate('yyyy-MM-dd hh:mm:ss', values)
                break;
            case 'date':
                return $Utils.formatDate('yyyy-MM-dd', values)
                break;
            case 'map':
                if(!column.formatMap){
                    return values;
                }
                return  $Arrays.arrayLookup(column.formatMap,'value', values, 'label')
                break;
            default:
                return values;
        }
    }
}


